<template>
  <a-drawer :visible="visible" :closable="false" width="auto" @close="closeModel">
    <div class="disFlx selectedUserBox">
      <div v-if="postParams.type === 1 && selectedRows.length" style="width: 250px;" class="_mr-20">
        <a-list size="small" bordered :data-source="selectedRows">
          <a-list-item slot="renderItem" slot-scope="item, index">
            <span class="ov-1">{{ item.personName }}</span>
            <span class="ov-1">{{ item.personTel }}</span>
            <a-tag color="red" @click="removeSelected(index)">移除</a-tag>
          </a-list-item>
          <div slot="header" class="fw-6 disFlxJS">
            <span>已选择人员</span>
            <a-tag color="red" @click="onSelectChange([], [])">全部移除</a-tag>
          </div>
        </a-list>
      </div>
      <div class="drawerBox">
        <div class="disFlxJS">
          <a-radio-group v-model="queryParam.lockSeat" @change="getTableData" button-style="solid">
            <a-radio-button :value="false" class="_pl-40 _pr-40"> 待分配 </a-radio-button>
            <a-radio-button :value="true" class="_pl-40 _pr-40"> 已分配 </a-radio-button>
          </a-radio-group>
          <div>
            <a-button v-if="postParams.type !== 4" type="primary" class="_ml-10" @click="handleAddUser"
              >新增用户报名</a-button
            >
            <a-button v-if="postParams.type !== 4" type="solid" class="_ml-10" @click="openBatchAddUser"
              >批量代报名</a-button
            >
          </div>
        </div>
        <div class="disFlxAC">
          <a-form layout="inline" class="_mt-10" style="flex: 1">
            <a-form-item label="关键字:">
              <a-input v-model="queryParam.keyWord" placeholder="姓名、手机号、单位名称搜索" style="width: 215px" />
            </a-form-item>
            <a-form-item label="会员职务:">
              <a-select v-model="queryParam.levelId" placeholder="请选择会员职务" allowClear style="width: 150px">
                <a-select-option v-for="item in levelList" :value="item.id" :key="item.id"
                  >{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="参会者标签:">
              <a-select
                v-model="queryParam.labelIds"
                mode="multiple"
                style="width: 437px"
                placeholder="请选择参会者标签进行筛选"
              >
                <a-select-option v-for="item in labelOptions" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="信息收集表">
              <div style="width: 437px">
                <SelectCustomForm :activityId="activityId" ref="SelectCustomForm" />
              </div>
            </a-form-item>
            <a-form-item label="报名类型">
              <a-select v-model="queryParam.activityTicketId" placeholder="请选择报名类型" allowClear style="width: 150px">
                <a-select-option v-for="item in ticketList" :key="item.value" :value="item.id">{{
                  item.ticketName
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
          <div class="_pt-11">
            <div><a-button @click.stop="resetSearch">重置</a-button></div>
            <div class="_mt-7"><a-button type="primary" @click.stop="getTableData">查询</a-button></div>
          </div>
        </div>
        <div class="_pt-5 _pb-5" v-if="queryParam.lockSeat">
          已分配<span style="color: red">{{ total }}</span
          >人
        </div>
        <div class="_pt-5 _pb-5" v-else>
          待分配<span style="color: red">{{ total }}</span
          >人, 已选择<span style="color: red">{{ selectedRowKeys.length }}</span
          >人
        </div>

        <STable
          size="default"
          ref="table"
          rowKey="id"
          :columns="selectUserTableColumns(queryParam.lockSeat)"
          :data="loadData"
          :loading="loading"
          :pageSize="20"
          paginationSize="small"
          style="height: calc(100vh - 430px);"
          :scroll="{ y: 'calc(100vh - 430px)', x: 575 }"
          :rowSelection="
            queryParam.lockSeat || postParams.type === 4
              ? null
              : {
                  selectedRowKeys: selectedRowKeys,
                  type: postParams.type === 1 ? 'checkbox' : 'radio',
                  onChange: onSelectChange
                }
          "
          bordered
        >
          <!-- 参会者信息 -->
          <div slot="personInfo" slot-scope="text, record">
            <div>{{ record.personName }}</div>
            <div>{{ record.personTel }}</div>
          </div>
          <!-- 单位信息 -->
          <div slot="companyInfo" slot-scope="text, record">
            <a-tooltip :title="record.companyName">
              <div class="w-[200px] ov-1">{{ record.companyName }}</div>
            </a-tooltip>
            <div v-if="record.companyPosition" class="companyInfoTag">{{ record.companyPosition }}</div>
          </div>
          <!-- 来源组织信息 -->
          <div slot="sourceInfo" slot-scope="text, record">
            <a-tooltip :title="record.orgName">
              <div class="w-[120px] ov-1">{{ record.orgName }}</div>
            </a-tooltip>
            <a-tag v-if="!record.identity">非会员</a-tag>
            <a-tag v-else color="orange">{{ record.memberLevelName }}</a-tag>
          </div>
        </STable>
        <div style="flex: 1"></div>
        <div class="btnBox">
          <a-button type="solid" class="_ml-5" @click="closeModel">取 消</a-button>
          <a-button type="primary" class="_ml-10" @click="debounce(submit)">确 定</a-button>
        </div>
      </div>
    </div>

    <!-- 添加报名用户 -->
    <UserCustomFormModal ref="userCustomFormModal" :activityId="activityId" :rowData="{}" @success="handleAddSuccess" />
  </a-drawer>
</template>

<script>
import { STable } from '@/components'
import { selectUserTableColumns } from './columns.js'
import { memberLevel } from '@/api/member/memberType'
import { activityArrangeRegisterList, getActivityLabelList, getTicketList } from '@/api/activity/activity'
import { debounce } from '@/utils/common'
import { cloneDeep } from 'lodash-es'
import UserCustomFormModal from '@/views/activity/components/customFormModal/index.vue'
import SelectCustomForm from '@/components/selectCustomForm'

export default {
  components: {
    STable,
    UserCustomFormModal,
    SelectCustomForm
  },
  props: {
    // 活动ID
    activityId: {
      type: Number | String
    },
    // 场次ID
    activityArrangeId: {
      type: Number | String
    }
  },
  data() {
    return {
      selectUserTableColumns,
      visible: false,
      levelList: [], // 会员职称List
      labelOptions: [], // 標簽列表
      loading: false,
      ticketList: [],
      queryParam: {
        activityTicketId: undefined,
        lockSeat: false, //true 已分配   false 待分配
        keyWord: undefined, // 关键字查询
        levelId: undefined, // 职务
        labelIds: [] // 标签列表
      },
      total: 0, // 当前总数
      loadData: async parameter => {
        return activityArrangeRegisterList({
          ...parameter,
          activityId: this.activityId,
          activityArrangeId: this.activityArrangeId,
          ...this.queryParam
        }).then(res => {
          this.total = res.data.total
          return res
        })
      },
      postParams: {
        type: 1
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  methods: {
    debounce,
    handelTicketListDownList() {
      return getTicketList(this.activityId).then(res => {
        if (res.code === 0) {
          this.ticketList = res.data || []
        }
      })
    },
    openModel(type, groupId, seatId) {
      this.postParams = {
        type, // 1: 批量选择人员 2.指定座位添加人员 3.指定座位添加人员(座位为占座) 4.只查看分配情况,不进行选择操作
        groupId,
        seatId: seatId || undefined
      }

      // 弹窗初始化 start
      this.selectedRowKeys = []
      this.selectedRows = []
      this.resetSearch()
      this.getTypeList()
      this.getLabelList()
      this.handelTicketListDownList()
      // 弹窗初始化 end

      this.visible = true
    },
    closeModel() {
      this.visible = false
    },

    submit() {
      if (this.postParams.type === 4) {
        this.closeModel()
        return
      }
      if (!this.selectedRowKeys.length) {
        this.$message.warning('未选择人员')
        return
      } else {
        if (this.postParams.type === 1) {
          const usetList = this.selectedRowKeys.map(v => {
            return {
              userId: v //报名人员id
            }
          })
          this.$emit('submit', { ...this.postParams, usetList })
        } else {
          this.$emit('submit', {
            ...this.postParams,
            ...{
              userId: this.selectedRows[0].id,
              userName: this.selectedRows[0].personName, //姓名
              userCompanyName: this.selectedRows[0].companyName, //公司名称
              userPosition: this.selectedRows[0].memberLevelName //会员职务
            }
          })
        }
      }
    },
    resetSearch() {
      this.$refs.SelectCustomForm && this.$refs.SelectCustomForm.resetData()
      Object.assign(this.$data.queryParam, this.$options.data().queryParam)
      this.getTableData()
    },
    // 获取表格数据
    getTableData() {
      if (this.$refs.SelectCustomForm) {
        const customFormItem = this.$refs.SelectCustomForm.getQueryParams()
        this.$set(this.queryParam, 'itemId', customFormItem ? customFormItem.itemId : undefined)
        this.$set(this.queryParam, 'itemAnswerId', customFormItem ? customFormItem.itemAnswerId : undefined)
        this.$set(this.queryParam, 'itemValue', customFormItem ? customFormItem.itemValue : undefined)
      }
      this.$refs.table && this.$refs.table.refresh(true)
    },
    // 组织类型下拉
    getTypeList() {
      memberLevel().then(res => {
        this.levelList = res.data
      })
    },
    // 获取标签列表
    getLabelList() {
      getActivityLabelList(this.activityId).then(res => {
        this.labelOptions = res.data
      })
    },
    //表格数据选中 selectedRows 翻页数据未保存
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys

      // 保留和selectedRowKeys对应的row
      let selectedList = []
      const rows = [...selectedRows, ...this.selectedRows]
      this.selectedRowKeys.forEach(v => {
        const selectedUser = rows.find(row => row.id === v)
        selectedUser && selectedList.push(selectedUser)
      })
      this.selectedRows = selectedList
    },
    removeSelected(index) {
      const selectedRowKeys = cloneDeep(this.selectedRowKeys)
      selectedRowKeys.splice(index, 1)
      this.onSelectChange(selectedRowKeys, [])
    },
    //打开新增用户报名弹窗
    handleAddUser() {
      this.$refs.userCustomFormModal.openModal({}, 'add')
    },
    //新增用户报名成功
    handleAddSuccess(user) {
      this.getTableData()
      this.selectedRows.push(user) // 默认勾选
      this.selectedRowKeys.push(user.id) // 默认勾选
    },
    // 打开批量代报名窗口
    openBatchAddUser() {
      window.open(`${window.origin}/activity/registrationList?openApply=${this.activityId}`)
    }
  },
  mounted() {
    const _this = this
    window.addEventListener(
      'message',
      function(e) {
        const { location } = e.source
        if (location.pathname === '/activity/registrationList' && e.data === 'Refresh') {
          _this.getTableData() // 刷新报名人员列表
        }
      },
      false
    )
  }
}
</script>

<style lang="less" scoped>
.drawerBox {
  width: 615px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .btnBox {
    display: flex;
    justify-content: flex-end;
    position: absolute;
    right: 20px;
    bottom: 20px;
  }
}
.selectedUserBox /deep/ .ant-list .ant-spin-container {
  height: calc(100vh - 170px);
  overflow-y: auto;
}
.selectedUserBox /deep/ .formItem {
  width: 100%;
  .ant-form-item-control-wrapper {
    width: 100%;
  }
}
.companyInfoTag {
  display: inline-block;
  background: #e8f7ff;
  color: #3491fa;
  padding: 1px 8px;
  border-radius: 2px;
}
</style>
